package edu.hnu.tradeserver.controller;

import edu.hnu.commonutils.EnumResultCode;
import edu.hnu.commonutils.Result;
import edu.hnu.commonutils.UserDb.TradersResponse;
import edu.hnu.commonutils.model.User;
import edu.hnu.tradeserver.auth.JwtOperator;
import edu.hnu.tradeserver.entity.Trades;
import edu.hnu.tradeserver.feign.UserFeign;
import edu.hnu.tradeserver.service.TradesService;
import edu.hnu.tradeserver.service.TransactionService;
import java.util.List;

import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
//@CrossOrigin(origins = "*")
@RequestMapping("/trade")
@Api(value = "交易流程接口",tags = {"trade"})
public class TradeController {
    @Autowired
    TradesService tradeService;
    @Autowired
    UserFeign userFeign;


    @Autowired
    JwtOperator jwtOperator;
    private User parseToken(String token){
        Claims claims = jwtOperator.getClaimsFromToken(token);
        User user = new User(-1L,-2,false);
        try {
            Long id = Long.parseLong(claims.get("id").toString());
            int userType= Integer.parseInt(claims.get("user_type").toString());
            if (userType != 1) {
                // 判断是否是不是生产商
                user.setAuthorized(false);
            }else {
                user.setUserType(userType);
                user.setId(id);
                user.setAuthorized(true);
            }
        } catch (NumberFormatException e) {
            user.setAuthorized(false);
            return user;
        }
        return user;
    }
    @GetMapping("/tradesInfo")
    public Result tradeInfo(@RequestParam("timeRange") String timeRange){
        List<Trades> tradesList = tradeService.getTradesInfo(timeRange);
        return Result.ok().data(tradesList);
    }

    @PostMapping("/createTrade")
    public Result createTrade(@RequestHeader("token") String token,@RequestBody Trades trades) {
        User user = parseToken(token);
        if(!user.isAuthorized()){
            return Result.error(EnumResultCode.UNAUTHORIZED);
        }
        System.out.println(user.getUserType());
        System.out.println(user.getId());
        return tradeService.createTrade(trades);
    }

    @GetMapping("/TestTraderDetail")
    public Result<TradersResponse> TestTraderDetail(Integer id){
        TradersResponse tradersResponse= userFeign.getTraderDetail(id);

        return Result.ok().data(tradersResponse);
    }

}
